﻿using System.IO;
using LoungeRepo.Contracts.EntityStore;

namespace LoungeRepo.EntityStore
{
    partial class FilesystemEntityStore
    {
        internal void Store(Stream target, IStreamedEntity streamedEntity)
        {
            streamedEntity.Blob.Seek(0, SeekOrigin.Begin);
            CopyStream(target, streamedEntity.Blob);
        }

        internal IStreamedEntity Load(string id, string partition, Stream source)
        {
            var streamEntity = new ReadWriteStreamedEntity { Id = id, Partition = partition };
            CopyStream(streamEntity.Blob, source);
            return streamEntity;
        }


        private void CopyStream(Stream target, Stream source)
        {
            byte[] buffer = new byte[4 * 1024];
            do
            {
                int n = source.Read(buffer, 0, buffer.Length);
                if (n <= 0) break;
                target.Write(buffer, 0, n);
            } while (true);
        }
    }
}
